﻿using AlibabaCloud.OpenApiClient.Models;
using LVYAN.Model;
using LVYAN.Model.AutoMation;
using LVYAN.Service.AIAPI;
using LVYAN.Utils;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Text;
using Tea;

namespace LVYAN.Service
{
    public class BaiLianService
    {
        /// <summary>
        /// 文档Key
        /// </summary>
        /// <returns></returns>
        public ResponseMessage Generation(RobotRobotOther Robot, RoomConfigModel RoomConfig, string SessionId, string MemoryId, string Message, string NickName)
        {
            if (string.IsNullOrWhiteSpace(Message))
            {
                return new ResponseMessage { Success = false, };
            }
            var CurrentMessage = Message;
            if (string.IsNullOrWhiteSpace(SessionId)) Message += Robot.RobotPrompt;

            BaiLianRequestGeneration wenGeneration = new BaiLianRequestGeneration
            {
                input = new BaiLianInput
                {
                    prompt = Message,
                    memory_id = MemoryId,
                    session_id = SessionId,
                    biz_params = new Dictionary<string, object> {
                        { "NickName",NickName},
                        { "RobotId",Robot.Id},
                        { "Contents",CurrentMessage},
                        { "Url",""},
                    },
                },
                parameters = new BaiLianParameters
                {
                    rag_options = new BaiLianrag_options
                    {
                        file_ids = RoomConfig.FileIds.SplitObj(),
                        pipeline_ids = RoomConfig.PipelineIds.SplitObj(),
                        structured_filter = JsonService.ToModel<Dictionary<string, object>>(RoomConfig.StructuredFilter),
                        tags = RoomConfig.FileTags.SplitObj()
                    }
                },
            };
            var content = JsonService.ToString(wenGeneration);
            new LoggerService().ResponseMsgDebug("百炼模型", "发送消息", content);
            var result = new RequestService().PostJson($"https://dashscope.aliyuncs.com/api/v1/apps/{RoomConfig.BaiLianKEY}/completion", content, new List<(string, string)> { ("Authorization", $"Bearer {RoomConfig.MouldeKEY}") });
            if (string.IsNullOrWhiteSpace(result))
            {
                return new ResponseMessage { Success = false, };
            }
            new LoggerService().ResponseMsgDebug("百炼模型", "接收消息", result);

            var resultModel = JsonService.ToModel<BaiLianResponseGeneration>(result);
            var response = new ResponseMessage { Success = true, Message = resultModel.output.text, RequestId = "", ResponseId = resultModel.output.session_id, modelid = resultModel.usage.models[0].model_id, Role = "", InputToken = resultModel.usage.models[0].input_tokens, OutToken = resultModel.usage.models[0].output_tokens }; ;
            MoudleManage.ModuleRecord(Robot, Message, content, result, response.InputToken ?? 0, response.OutToken ?? 0);
            return response;
        }


        /// <summary>
        /// 文档Key
        /// </summary>
        /// <returns></returns>
        public ResponseMessage CreateMemoryId(RobotRobotOther Robot, RoomConfigModel RoomConfig, string Description)
        {
            AlibabaCloud.SDK.Bailian20231229.Client client = CreateClient();
            AlibabaCloud.SDK.Bailian20231229.Models.CreateMemoryRequest createMemoryRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateMemoryRequest() { Description = Description, };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            Dictionary<string, string> headers = new Dictionary<string, string>() { };
            try
            {
                var result1 = client.CreateMemoryWithOptions(RoomConfig.WorkspaceId, createMemoryRequest, headers, runtime);
                var response = new ResponseMessage { Success = true, RequestId = result1.Body.RequestId, ResponseId = result1.Body.MemoryId, };
                return response;
            }
            catch (TeaException error)
            {
                return new ResponseMessage { Success = false, Message = error.Message };
            }
            catch (Exception _error)
            {
                return new ResponseMessage { Success = false, Message = _error.Message };
            }
        }

        public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
        {


            // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378671.html。
            Config config = new Config()
            {
                Type = "access_key",
                AccessKeyId = "LTAI5tDv1Gwj5CS93zKspqf9",
                AccessKeySecret = "OJH3WUVyV2FmdWlvzcSNkMcyM2hiC0"
            };
            // Endpoint 请参考 https://api.aliyun.com/product/bailian
            config.Endpoint = "bailian.cn-beijing.aliyuncs.com";
            return new AlibabaCloud.SDK.Bailian20231229.Client(config);
        }
    }
}
